package org.opens.netty.udp.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.opens.netty.udp.entity.LogEvent;

import java.nio.charset.Charset;
import java.util.List;

public class LogEventDecode extends MessageToMessageDecoder<DatagramPacket> {

    @Override
    protected void decode(ChannelHandlerContext ctx, DatagramPacket datagramPacket, List<Object> out) throws Exception {
        ByteBuf data = datagramPacket.content();
        int idx = data.indexOf(0, data.readableBytes(), LogEvent.SEPARATOR);
        String filename = data.slice(0, idx).toString(Charset.defaultCharset());
        String logMsg = data.slice(idx + 1, data.readableBytes()).toString(Charset.defaultCharset());
        LogEvent logEvent = new LogEvent(datagramPacket.sender(), System.currentTimeMillis(), filename, logMsg);
        out.add(logEvent);
    }

}
